﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace SuperMarket
{
    public class Storage
    {
        private static Dictionary<Guid, List<BaseProduct>> productInfo = null;

        /// <summary>
        /// 将商品添加到对应库存
        /// </summary>
        /// <param name="product"></param>
        /// <returns></returns>
        public static bool Add(BaseProduct product)
        {
            try
            {
                if (productInfo == null)
                {
                    productInfo = new Dictionary<Guid, List<BaseProduct>>();
                }

                if (!productInfo.ContainsKey(product.SPU))
                {
                    productInfo[product.SPU] = new List<BaseProduct>();
                }
                productInfo[product.SPU].Add(product);
                return true;
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception!!!");
                Console.WriteLine(e);
                return false;
            }
        }

        /// <summary>
        /// 获取所有spu
        /// </summary>
        /// <returns></returns>
        public static List<Guid> GetAllSpu()
        {
            List<Guid> result = new List<Guid>();
            foreach (Guid spu in productInfo.Keys)
            {
                result.Add(spu);
            }
            return result;
        }

        /// <summary>
        /// 获取指定spu的库存商品数量
        /// </summary>
        /// <param name="spu"></param>
        /// <returns></returns>
        public static int GetProductNum(Guid spu)
        {
            return productInfo[spu].Count;
        }

        /// <summary>
        /// 获取指定spu和数量的List，相当于从库存取货
        /// </summary>
        /// <param name="spu"></param>
        /// <param name="count"></param>
        /// <returns></returns>
        public static List<BaseProduct> GetProducts(Guid spu, int count)
        {
            List<BaseProduct> result = new List<BaseProduct>();
            for (int i = 0; i < count; i++)
            {
                if (productInfo[spu].Count == 0) {
                    break;
                }
                result.Add(productInfo[spu][0]);
                productInfo[spu].RemoveAt(0);
            }
            return result;
        }
    }
}
